package com.ruyuan.commodity.consumer.core.receiver;

import cn.hutool.json.JSONUtil;
import com.ruyuan.commodity.open.api.model.base.message.GoodsChangeMsg;
import com.ruyuan.commodity.open.api.model.base.rabbitmq.AmqpExchange;
import com.ruyuan.commodity.consumer.core.event.GoodsChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * 商品变化消费者
 */
@Component
public class GoodsChangeReceiver {

	private final Logger LOG = LoggerFactory.getLogger(getClass());

	@Autowired
	private List<GoodsChangeEvent> goodsChangeEvents;

	/**
	 * 商品变化
	 * 
	 * @param goodsChangeMsg 商品信息变更的消息
	 */
	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(value = AmqpExchange.GOODS_CHANGE + "_QUEUE"),
			exchange = @Exchange(value = AmqpExchange.GOODS_CHANGE, type = ExchangeTypes.FANOUT)
	))
	public void goodsChange(GoodsChangeMsg goodsChangeMsg) {
		LOG.info("接收到 商品发生变化的消息 消息内容为 [{}]", JSONUtil.toJsonStr(goodsChangeMsg));

		if (goodsChangeEvents != null) {
			for (GoodsChangeEvent event : goodsChangeEvents) {
				try {
					event.goodsChange(goodsChangeMsg);
				} catch (Exception e) {
					LOG.error("处理商品变化消息出错", e);
					e.printStackTrace();
				}
			}
		}
	}

}
